#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <wait.h>
#define MAX_LINE 80

int main(){
    int h_id=1;
    char *args[MAX_LINE][MAX_LINE];
    int should_run = 1;
     for(int i=0;i<MAX_LINE;i++){
       
        for(int j=0;j<MAX_LINE;j++){
            args[i][j] = (char*)malloc(20*sizeof(char));
        }
    }
    
    while(should_run){
        if(strcmp(args[h_id-1][0],"!!") == 0){
           if(h_id-2>0){
               for(int i = 0;i<10;i++){
                   args[h_id][i]=args[h_id-2][i];
               }
           }
        
            else{
            printf("历史命令不存在");
            printf("2019112118@OS2021$>");
            int j =0;
            do{
              scanf("%s",args[h_id][j]);
                j++;
         }
            while(getchar()!='\n');
            args[h_id][j] = NULL;
          }
        }
    else {
        printf("2019112118@OS2021$>");
         int j1 =0;
         do{
              scanf("%s",args[h_id][j1]);
                j1++;
         }
            while(getchar()!='\n');
               
            
            args[h_id][j1] = NULL;
        }

    pid_t pid = fork();
    if(pid < 0){
         fprintf(stderr,"子进程创建失败");
    }
    else if(pid ==0){
        if(strcmp(args[h_id][0],"history")==0){
            for(int i =h_id;i>0;i--){
                printf("第%d个指令%s",i,args[i][0]);
                printf("2019112118@OS2021$>");
            }
        }
        else if(strcmp(args[h_id][0],"exit")==0){
            printf("退出程序");
            should_run=0;
            _exit(2);
            break;
        }
        else if(strcmp(args[h_id][0],"!!")==0){


        }
        else{
            int k = execvp(args[h_id][0],args[h_id]);
               
                if(k < 0){
                    printf("找不到文件\n");
                    printf("2019112118@OS2021$>");
                }
        }
    
   

    }
            h_id++;
            fflush(stdout);
    }
}

